//
//  TestTableVCPresent.swift
//  SunxianhuaTestApp
//
//  Created by abc on 2021/10/11.
//

import Foundation


protocol NewsTableViewModelDelegate :AnyObject{
    func reloadView(isHaveMoreData :Bool)
}


class NewsTableViewPresent {
    
    var currentPage :Int = 0
    var dataArray :[ArticleItemModel] = Array()
    weak var delegate :NewsTableViewModelDelegate?
    
    //发起请求
    func requestMoreData(isRefesh :Bool = true){
        
        if !isRefesh {
            //从本地取
            TaskQueue.init().addOperation {
                
                guard let jsonString = CacheDataTool.getValue(ofKey: AppConfiguration.newsJsonKey) as? String,let model = ArticleListModel.deserialize(from: jsonString) else {
                    HUD.showWait("加载中...")
                    return
                }
                self.handleData(listModel: model)
                self.delegate?.reloadView(isHaveMoreData: false)
            }
            return
        }
        
        
        //从网络取
        dataArray.removeAll()
        let url = AppConfiguration.baseUrl + "v2/top-headlines?country=us" + "&apiKey=\(AppConfiguration.appKey)"
        TestHttpsTool.init().requestNewsData(url: url) {[weak self] listModel in
            guard let weakSelf = self else {return}
            TaskQueue.init().addOperation {
                
                if let json = listModel.toJSONString() {
                    CacheDataTool.save(value: json, toKey: AppConfiguration.newsJsonKey)
                }
                weakSelf.handleData(listModel: listModel)
                weakSelf.delegate?.reloadView(isHaveMoreData: false)
            }
        } failCallBlock: { _ in
            
        }
    }
    
    func handleData(listModel :ArticleListModel){
        listModel.handleData()
        self.dataArray = listModel.articles
        
    }
    
    func clearData(){
        
        
        self.delegate?.reloadView(isHaveMoreData: true)
    }
    
    //数据处理
    
    
}
